fn main() {
    let ans = Solution::my_atoi(String::from("-123"));
    println!("{}", ans);
    let ans = Solution::my_atoi(String::from("- 123"));
    println!("{}", ans);
}

struct Solution;

impl Solution {
    pub fn my_atoi(s: String) -> i32 {
        let get_col = |c: char| -> usize {
            if c == ' ' {
                return 0;
            } else if c == '+' || c == '-' {
                return 1;
            } else if c.is_numeric() {
                return 2;
            } else {
                return 3;
            }
        };
        let max = i32::MAX / 10;
        // 状态机
        let arr = [[0, 1, 2, 3], [3, 3, 2, 3], [3, 3, 2, 3], [3, 3, 3, 3]];
        let mut ans = 0;
        let mut sign = 1;
        let mut state = 0;
        for c in s.chars() {
            state = arr[state][get_col(c)];
            if state == 1 {
                if c == '-' {
                    sign = -1;
                }
            } else if state == 2 {
                let tmp = c as i32 - 48;
                if sign == 1 {
                    if ans > max || (ans == max && tmp > 7) {
                        return i32::MAX;
                    }
                } else if sign == -1 {
                    if ans > max || (ans == max && tmp > 8) {
                        return i32::MIN;
                    }
                }
                ans = ans * 10 + (c as i32 - 48);
            } else if state == 3 {
                break;
            }
        }
        ans * sign
    }
}
